import React from 'react'
import { IconFont, info, success, Input, Button, TitleBar, Nav, NavContent, Link } from '../../ui-components'
import { Link as NewLink } from 'sq-ui';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as UserAction from '../../actions/user.action'
import { downloadDocument, saveUserProfile, fetchOnboardingTemplate, resetOnboardingTemplates } from '../../actions/onboarding.hr.action'
import { resetTeam, fetchReportees, fetchTeam, fetchReportor} from '../../actions/team.action'
import { resetOkr, fetchPeriod, fetchObjective } from '../../actions/okr.action'
import { fetchRewardsById } from '../../actions/kudos.action'
import { fetchAddresses } from '../../actions/app.action'
import { u } from '../../actions/util'
import styleNC from '../../ui-components/navContent/style'
import util from '../../util'
import cx from 'classnames'
import style from './style'
import { presets, StaggeredMotion, Motion, spring } from 'react-motion'

export default
@connect(({ user, app, kudos }) => ({ user, app, kudos }), dispatch => ({actions: bindActionCreators({ ...UserAction, fetchRewardsById, fetchTeam, fetchReportees , resetTeam, fetchObjective, fetchPeriod, resetOkr, fetchOnboardingTemplate, resetOnboardingTemplates, saveUserProfile, downloadDocument, fetchAddresses }, dispatch)}))
class User extends React.Component {

  state = {
    editSignature: false,
    signatureLine: ''
  }

  handleChangeSignature(e) {
    this.setState({
      signatureLine: e.target.value
    })
  }

  updateSignature() {
    info('更新签名中...', true)
    this.props.actions.updateUserProfile(this.props.params.userId, {
      'signatureLine': (this.state.signatureLine || '').trim()
    }, () => {
      success('更新签名成功!')
      this.props.actions.fetchUserProfile(this.props.params.userId, () => {
        this.setState({
          editSignature: false
        })
      })
    })
  }

	item = ({label,icon, to, name, active, index, target='_self'}) => {
		let _active
		if (!name) {
			_active = active && this.props.location.pathname.match(/\/user\/[^\/]+\/?$/)
		} else {
			_active = active && ~this.props.location.pathname.indexOf(name)
		}
		return (
			<Link 
        className={style['nav-link']}
        active={_active}
        target={target}
				iconRight={icon}
				to={to}
				label={label}
			/>
		)
	}

	static contextTypes = {
		router: React.PropTypes.object
	}

	componentDidMount() {
		this.fetchData()
	}

	componentWillUnmount() {
		this.props.actions.resetUser()
	}

	componentWillReceiveProps(props) {
		if (props.params.userId != this.props.params.userId) {
			this.props.actions.resetUser()
			this.fetchData(props)
      this.setState({
        editSignature: false,
        signatureLine: ''
      })
		}

    if (util.isNull(this.state.signatureLine) && !util.isNull(props.user.profile)) {
      this.setState({
        signatureLine: util.find(props.user.profile.profileFieldVOs, f => f.referenceName === 'signatureLine').dataValue
      })
    }
	}

  handleUpdateProfile() {
    if (util.isEqual(this.getUserId(), u.userId)){
      this.context.router.push('/personal/basic')
    } else {
      this.context.router.push('/team/staffProfile/' + this.getUserId())
    }
  }

	fetchData(props) {
		props = props || this.props
		const userId = this.getUserId(props)
		this.props.actions.fetchUserCoreProfile(userId)
		this.props.actions.fetchUserProfile(userId)
    this.props.actions.fetchReportLineInfo(userId)
		this.props.actions.fetchRewardsById(userId)
	}

	getUserId(props) {
		return (props || this.props).params.userId || u.userId
	}

  renderSignature() {
    const { editSignature } = this.state
    const { profileFieldVOs=[] } = this.props.user.profile || {};
    const { signatureLine } = this.state
		const isSelf = util.isEqual(this.getUserId(), u.userId)
    if (!profileFieldVOs || !profileFieldVOs.length) return null
    if (!editSignature) {
      return (
        <div className={style.descr}>
          <div>{ signatureLine || '这家伙很懒，什么都没有留下来...'}</div>
          { 
            isSelf?
            <Link 
              size="12" 
              icon="modify" 
              className={style.edit} 
              onClick={() => {
                this.setState({ editSignature: true })
              }}
            />: null
          }
        </div>
      )
    } else { 
      return (
        <div className={style['edit-signature']} style={{marginBottom: '-10px'}}>
          <div data-role={'input'} >
            <Input 
              autoFocus 
              lineStyle
              width={250}
              value={this.state.signatureLine} 
              onChange={e => { this.setState({ signatureLine: e.target.value }) }}
            />
            </div>
            <Button label="保存" onClick={::this.updateSignature}/>
        </div>
      )
    }
  }

	render() {
		const { reportLineInfo, coreProfile, profile } = this.props.user
		let { team={}, reportors=[], reportees } = reportLineInfo
    if (reportors.length && !reportors._reverse) {
      reportors = reportors.reverse()
      reportors._reverse = true
    }
		const { profileFieldVOs=[] } = profile || {}
		const jobLevel = util.find(profileFieldVOs, item => item.referenceName === 'jobLevel')
		const jobLevelName = util.find((jobLevel.typeSpec || {}).pickOptions, opt => opt.pickOptionId == jobLevel.dataValue).optionValue

    const { jobTitleName, teamVO, projectTeamVOs } = coreProfile
		const userId = this.getUserId()
    const signatureLine = util.find(profileFieldVOs, item => item.referenceName === 'signatureLine')
		let navs = [
			[
				{to: `#/user/${userId}`, label:'首页', name: ''}, 
         {to: `#/okr?type=3&userId=${userId}&teamId=${(teamVO || {}).teamId}`, label: '工作目标', name: 'objective', target: '_blank'},
				{to: `#/user/${userId}/resume`, label: '个人简历', name: 'resume'},
			], 
		]

    const { roleNameList=[] } = this.props.app.profile
    const isHR = ~roleNameList.indexOf('HR')

		const isSelf = util.isEqual(userId, u.userId)
		if (!isSelf) navs = [navs[0]]
    return (
      <div>
        <div className={style.header}>
          <div className={style.account}>
            <Link
              noHover
              srcIcon="avatar"
              width="140"
              className={styleNC.avatar}
              src={coreProfile.avatarUrl}
            />
            <div>
              <div className={style['user-name']}>
                <div>
                  <h1>{ coreProfile.fullName }</h1>
                  { this.renderSignature() }
                </div>
              </div>
              {
                profileFieldVOs?
                <Motion defaultStyle={{ opacity: 0 }} style={{ opacity: spring(1) }}>
                  {
                    ({ opacity }) => (
                      <div className={style.info} style={{ opacity }}>
                        <div>
                          <label>职位:</label>
                          <span>{ jobTitleName || '' }</span>
                          <label style={{ marginLeft: '15px' }}>所在团队:</label>
                          <span>
                            <NewLink
                              target="_blank"
                              to={`/okr?type=2&teamId=${(teamVO || {}).teamId}`}
                              label={ (teamVO || {}).teamName || '' }
                            />
                          </span>
                          <label style={{ marginLeft: '15px' }}>所在项目组:</label>
                          <span>
                            {
                              (projectTeamVOs || []).map((g,i) => (
                                <span key={i}>
                                  <NewLink
                                    target="_blank"
                                    label={g.projectTeamName}
                                    to={`/okr/?type=4&teamId=${g.teamId}&projectTeamId=${g.projectTeamId}`}
                                  />
                                  {
                                    <span>{ i !== (projectTeamVOs || []).length-1 ? '，': '' }</span>
                                  }
                                </span>
                              ))
                            }
                          </span>
                        </div>
                        <div>
                          <label>级别:</label>
                          <span>{ jobLevelName || ((profileFieldVOs || []).length ? '无': '') }</span>
                        </div>
                        {
                          reportors.length?
                          <div>
                            <label>汇报关系:</label>
                              <span className={style['report-line']}>
                                {
                                  reportors.map((v, i) => (
                                    <NewLink 
                                      key={i}
                                      to={`#/user/${v.userId}`}
                                    >
                                      { v.fullName }
                                    </NewLink>
                                  ))
                                }
                                <span>{ coreProfile.fullName }</span>
                              </span>
                          </div>: (profileFieldVOs || []).length? (
                            <div>
                              <label>汇报关系:</label>
                              <span>无</span>
                            </div>
                          ): (
                            <div>
                              <label>汇报关系:</label>
                              <span></span>
                            </div>
                          )
                        }
                      </div>
                    )
                  }
                </Motion>: null
              }
            </div>
          </div>
          <div className={style.contacts}>
            {
              isSelf ?
              <Button label="修改资料" blueLine onClick={::this.handleUpdateProfile}/>
              :null
            }
            {
              !util.isNull(coreProfile)?
              <Motion defaultStyle={{ opacity: 0 }} style={{ opacity: spring(1) }}>
                {
                  ({ opacity }) => (
                    <div style={{ opacity }}>
                      <div>
                        <IconFont value="phone"/>
                        <span>{ coreProfile.mobilePhone }</span>
                      </div>
                      <div>
                        <IconFont value="email"/>
                        <span>{ coreProfile.emailAddress }</span>
                      </div>
                    </div>
                  )
                }
              </Motion>: null
            }
          </div>
        </div>
        <div className={style.body}>
          <Nav
            data={navs}
            item={this.item}
            className={cx({
              [styleNC.root]: true,
              [style.nav]: true
            })}
          />
          { 
            React.Children.map(this.props.children, child => React.cloneElement(child, {
              reportees,
              profileFieldVOs,
              isSelf,
              profile,
              kudos: this.props.kudos,
              getUserId: ::this.getUserId,
              ...this.props.actions
            })) 
          }
        </div>
      </div>
    )
		return (
			<div className={cx({
				[styleNC.root]: true,
				[styleNC.hasAvatar]: true
			})}>
				<Link
          srcIcon="avatar"
          width="140"
					className={styleNC.avatar}
					src={coreProfile.avatarUrl}
        />
				<Nav
					data={navs}
					item={this.item}
					className={cx({
						[styleNC.nav]: true,
						[style.nav]: true
					})}
				/>
				<div className={styleNC.content}>
					<div>
						<TitleBar 
							label={coreProfile.fullName} 
              leftActions={[
                ({ key }) => {
                  if (util.isNull(signatureLine)) return null
                  const { editSignature } = this.state
                  if (!editSignature) {
                    return (
                      <p key={key} className={style['modify-signature']}>
                        <span>{signatureLine.dataValue || '这家伙很懒，什么都没有留下..'}</span>
                        {
                          isSelf &&
                            <Link size="12" icon="modify" onClick={() => this.setState({editSignature: true })}/>
                        }
                      </p>
                    )
                  }
                  return (
                    <div key={key} className={style['update-signature']}>
                      <Input value={this.state.signatureLine} onChange={::this.handleChangeSignature} autoFocus/>
                      <div className={style['update-signature-actions']}>
                        <Link label="取消" color="red" onClick={() => this.setState({ editSignature: false })}/>
                        <Link label="更新" onClick={::this.updateSignature}/>
                      </div>
                    </div>
                  )
                }
              ]}
              actions={isSelf? [
                {
                  label: '修改资料',
                  handler: ::this.handleUpdateProfile
                }
              ]: []}
							/>
						<div className={style.info}>
							<p className={style.jobTitle}>
								{
									<span className={style.teamName}>{ team.teamName || '' }</span>
								}
                {
                  <span>-</span>
                }
								{
									<span>{ jobTitleName || '' }</span>
								}
								{
									jobLevelName?
									<span className={style['job-level']}>
										级别: { jobLevelName }
									</span>: null
								}
							</p>
							{
								reportors.length?
								<p className={style.reportLine}>
									<span>汇报关系:</span>
									{
										reportors.map((v, i) => (
											<span key={i} className={style.reportor}>
												<Link 
													to={`#/user/${v.userId}`}
												>
													{ v.fullName }
												</Link>
												<span>{ '->' }</span>
											</span>
										))
									}
									<span>{ coreProfile.fullName }</span>
								</p>: null
							}
						</div>
						{ 
							React.Children.map(this.props.children, child => React.cloneElement(child, {
								reportees,
								profileFieldVOs,
								isSelf,
								profile,
								getUserId: ::this.getUserId,
								...this.props.actions
							})) 
						}
					</div>
				</div>
			</div>
		)
	}
}
